<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="![Uploading 0_131088834611J5_092419.png . . .]###Java NIO学习使用 在Java1.4之前的I/O系统中，提供的都是面向流的I/O系统，系统一次一个字节地处理数据，一个输入流产生一个字节的数据，一个输出流消费一个字节的数据，面向流的I/O速度非常慢，而在Java 1.4中推出了NIO，这是一个面向块的I/O系统，系统以块的方式处理处理，每一个操">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Java-NIO学习使用">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Java/Java-NIO学习使用/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="![Uploading 0_131088834611J5_092419.png . . .]###Java NIO学习使用 在Java1.4之前的I/O系统中，提供的都是面向流的I/O系统，系统一次一个字节地处理数据，一个输入流产生一个字节的数据，一个输出流消费一个字节的数据，面向流的I/O速度非常慢，而在Java 1.4中推出了NIO，这是一个面向块的I/O系统，系统以块的方式处理处理，每一个操">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/3110861-c863dc48e94bbfad.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/3110861-452dd9b371e6b8a0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/3110861-3d21d36d893260cb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T10:45:44.595Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java-NIO学习使用">
<meta name="twitter:description" content="![Uploading 0_131088834611J5_092419.png . . .]###Java NIO学习使用 在Java1.4之前的I/O系统中，提供的都是面向流的I/O系统，系统一次一个字节地处理数据，一个输入流产生一个字节的数据，一个输出流消费一个字节的数据，面向流的I/O速度非常慢，而在Java 1.4中推出了NIO，这是一个面向块的I/O系统，系统以块的方式处理处理，每一个操">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/3110861-c863dc48e94bbfad.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Java/Java-NIO学习使用/"/>





  <title>Java-NIO学习使用 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Java/Java-NIO学习使用/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java-NIO学习使用</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:39+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>![Uploading 0_131088834611J5_092419.png . . .]###Java NIO学习使用</p>
<p>在Java1.4之前的I/O系统中，提供的都是面向流的I/O系统，系统一次一个字节地处理数据，一个输入流产生一个字节的数据，一个输出流消费一个字节的数据，面向流的I/O速度非常慢，而在Java 1.4中推出了NIO，这是一个面向块的I/O系统，系统以块的方式处理处理，每一个操作在一步中产生或者消费一个<a href="http://lib.csdn.net/base/mysql" target="_blank" rel="noopener">数据库</a>，按块处理要比按字节处理数据快的多。<br>在NIO中有几个核心对象需要掌握：缓冲区（Buffer）、通道（Channel）、选择器（Selector）。<br><a id="more"></a></p>
<p><strong>缓冲区Buffer</strong><br>缓冲区实际上是一个容器对象，更直接的说，其实就是一个数组，在NIO库中，所有数据都是用缓冲区处理的。在读取数据时，它是直接读到缓冲区中的； 在写入数据时，它也是写入到缓冲区中的；任何时候访问 NIO 中的数据，都是将它放到缓冲区中。而在面向流I/O系统中，所有数据都是直接写入或者直接将数据读取到Stream对象中。<br>在NIO中，所有的缓冲区类型都继承于抽象类Buffer，最常用的就是ByteBuffer，对于Java中的基本类型，基本都有一个具体Buffer类型与之相对应，它们之间的继承关系如下图所示：</p>
<p><img src="http://upload-images.jianshu.io/upload_images/3110861-c863dc48e94bbfad.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="Buffer.png"><br>使用示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">public static void start() &#123;</span><br><span class="line">	</span><br><span class="line">	/**</span><br><span class="line">	 * 分配新的int缓冲区，参数为缓冲区容量</span><br><span class="line">	 * 新缓冲区当前位置为零，其界限(限制位置)将为其容量</span><br><span class="line">	 * 它将具有一个底层实现数组，其数组偏移量将为零。</span><br><span class="line">	 */</span><br><span class="line">	IntBuffer buffer = IntBuffer.allocate(8);</span><br><span class="line">	// buffer.capacity()获取buffer的缓冲区长度</span><br><span class="line">	for(int i = 0; i &lt; buffer.capacity(); i++)&#123;</span><br><span class="line">		int j = 2 * (i + 1);</span><br><span class="line">		// 将给定整数写入此缓冲区的当前位置，当前位置递增</span><br><span class="line">		buffer.put(j);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	// 重设此缓冲区， 将限制设置为当前位置，然后将当前位置设置为0</span><br><span class="line">	buffer.flip();</span><br><span class="line">	</span><br><span class="line">	// 查看在当前位置和限制位置之间是否有元素</span><br><span class="line">	while(buffer.hasRemaining())&#123;</span><br><span class="line">		// 读取此缓冲区当前位置的整数，然后当前位置递增</span><br><span class="line">		int j = buffer.get();</span><br><span class="line">		System.out.println(j);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">2</span><br><span class="line">4</span><br><span class="line">6</span><br><span class="line">8</span><br><span class="line">10</span><br><span class="line">12</span><br><span class="line">14</span><br><span class="line">16</span><br></pre></td></tr></table></figure></p>
<p><strong>通道Channel</strong><br>通道是一个对象，通过它可以读取和写入数据，当然了所有数据都通过Buffer对象来处理。我们永远不会将字节直接写入通道中，相反是将数据写入包含一个或者多个字节的缓冲区。同样不会直接从通道中读取字节，而是将数据从通道读入缓冲区，再从缓冲区获取这个字节。<br>在NIO中，提供了多种通道对象，而所有的通道对象都实现了Channel接口。它们之间的继承关系如下：</p>
<p><img src="http://upload-images.jianshu.io/upload_images/3110861-452dd9b371e6b8a0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="0_1310888420STkI.png"><br><strong>使用NIO读取数据</strong><br>在前面我们说过，任何时候读取数据，都不是直接从通道读取，而是从通道读取到缓冲区。所以使用NIO读取数据可以分为下面三个步骤： </p>
<ol>
<li>从FileInputStream获取Channel </li>
<li>创建Buffer </li>
<li>将数据从Channel读取到Buffer中<br>下面是一个简单的使用NIO从文件中读取数据的例子：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">public static void readFile() throws IOException &#123;</span><br><span class="line">	// 创建文件输入流</span><br><span class="line">	FileInputStream fis = new FileInputStream(&quot;E:\\test.txt&quot;);</span><br><span class="line">	// 获取通道</span><br><span class="line">	FileChannel fc = fis.getChannel();</span><br><span class="line">	// 创建缓冲区</span><br><span class="line">	ByteBuffer buffer = ByteBuffer.allocate(1024);</span><br><span class="line">	// 读取到缓冲区</span><br><span class="line">	fc.read(buffer);</span><br><span class="line">	buffer.flip();</span><br><span class="line">	</span><br><span class="line">	byte[] bytes = new byte[1024];</span><br><span class="line">	int i = 0;</span><br><span class="line">	while(buffer.remaining() &gt; 0)&#123;</span><br><span class="line">		byte b = buffer.get();</span><br><span class="line">		bytes[i++] = b;</span><br><span class="line">	&#125;</span><br><span class="line">	System.out.println(new String(bytes,&quot;UTF-8&quot;));</span><br><span class="line">	fis.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>打印结果：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">?在前面我们说过，任何时候读取数据，都不是直接从通道读取，而是从通道读取到缓冲区。所以使用NIO读取数据可以分为下面三个步骤：</span><br><span class="line">从FileInputStream获取Channel</span><br><span class="line">创建Buffer</span><br><span class="line">将数据从Channel读取到Buffer中</span><br></pre></td></tr></table></figure></p>
<p><strong>使用NIO写入数据</strong><br>使用NIO写入数据与读取数据的过程类似，同样数据不是直接写入通道，而是写入缓冲区，可以分为下面三个步骤： </p>
<ol>
<li>从FileInputStream获取Channel </li>
<li>创建Buffer </li>
<li>将数据从Channel写入到Buffer中</li>
</ol>
<p>下面是一个简单的使用NIO向文件中写入数据的例子：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">public static void writeFile() throws IOException &#123;</span><br><span class="line">	// 要写入的数据</span><br><span class="line">	final byte message[] = &#123; 83, 111, 109, 101, 32,  </span><br><span class="line">	        98, 121, 116, 101, 115, 46 &#125;; </span><br><span class="line">	// 创建输出流</span><br><span class="line">	FileOutputStream fos = new FileOutputStream(&quot;E:\\test1.txt&quot;);</span><br><span class="line">	// 获取通道</span><br><span class="line">	FileChannel fc = fos.getChannel();</span><br><span class="line">	// 创建缓冲区</span><br><span class="line">	ByteBuffer buffer = ByteBuffer.allocate(1024);</span><br><span class="line">	</span><br><span class="line">	for(int i = 0; i &lt; message.length; i++)&#123;</span><br><span class="line">		buffer.put(message[i]);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	buffer.flip();</span><br><span class="line">	</span><br><span class="line">	fc.write(buffer);</span><br><span class="line">	</span><br><span class="line">	fos.close();</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>写入结果:<br><img src="http://upload-images.jianshu.io/upload_images/3110861-3d21d36d893260cb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="test1.png"></p>
<p><strong>NIO中非阻塞I/O编写服务器处理程序</strong><br>使用NIO中非阻塞I/O编写服务器处理程序，大体上可以分为下面三个步骤：</p>
<ol>
<li>向Selector对象注册感兴趣的事件 </li>
<li>从Selector中获取感兴趣的事件 </li>
<li>根据不同的事件进行相应的处理</li>
</ol>
<p>Server端：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br></pre></td><td class="code"><pre><span class="line">public class NioServer &#123;</span><br><span class="line">	/**</span><br><span class="line">	 * 监听的端口</span><br><span class="line">	 */</span><br><span class="line">	private static final int PORT = 8001;</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	 * 1. 注册事件 </span><br><span class="line">	 * 创建了ServerSocketChannel对象，并调用configureBlocking()方法，配置为非阻塞模式，</span><br><span class="line">	 * 接下来的三行代码把该通道绑定到指定端口，最后向Selector中注册事件，此处指定的是参数是OP_ACCEPT，</span><br><span class="line">	 * 即指定我们想要监听accept事件，也就是新的连接发 生时所产生的事件，对于ServerSocketChannel通道</span><br><span class="line">	 * 来说，我们唯一可以指定的参数就是OP_ACCEPT。</span><br><span class="line">	 * @throws IOException </span><br><span class="line">	 */</span><br><span class="line">	public Selector	getSelector() throws IOException &#123;</span><br><span class="line">		// 创建Selector</span><br><span class="line">		Selector selector = Selector.open();</span><br><span class="line">		</span><br><span class="line">		// 创建可选择通道，并配置为非阻塞模式</span><br><span class="line">		ServerSocketChannel server = ServerSocketChannel.open();</span><br><span class="line">		server.configureBlocking(false);</span><br><span class="line">		</span><br><span class="line">		// 绑定通道到指定的端口</span><br><span class="line">		ServerSocket socket = server.socket();</span><br><span class="line">		InetSocketAddress address = new InetSocketAddress(PORT);</span><br><span class="line">		socket.bind(address);</span><br><span class="line">		</span><br><span class="line">		// 向Selector中注册感兴趣的事件</span><br><span class="line">		server.register(selector, SelectionKey.OP_ACCEPT);</span><br><span class="line">		</span><br><span class="line">		return selector;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	/**</span><br><span class="line">	 * 2. 开始监听</span><br><span class="line">	 * 在非阻塞I/O中，内部循环模式基本都是遵循这种方式。首先调用select()方法，该方法会阻塞，</span><br><span class="line">	 * 直到至少有一个事件发生，然后再使用selectedKeys()方法获取发生事件的SelectionKey，</span><br><span class="line">	 * 再使用迭代器进行循环。</span><br><span class="line">	 */</span><br><span class="line">	public void listener(Selector selector) &#123;</span><br><span class="line">		try&#123;</span><br><span class="line">		while(true)&#123;</span><br><span class="line">			// 该调用会阻塞，知道至少有一个事件发生</span><br><span class="line">			selector.select();</span><br><span class="line">			// 当有事件可用的时候</span><br><span class="line">			Set&lt;SelectionKey&gt; keys = selector.selectedKeys();</span><br><span class="line">			// 遍历结合键</span><br><span class="line">			Iterator&lt;SelectionKey&gt; iterator = keys.iterator();</span><br><span class="line">			while (iterator.hasNext()) &#123;</span><br><span class="line">				SelectionKey key = iterator.next();</span><br><span class="line">				iterator.remove();</span><br><span class="line">				process(selector,key);</span><br><span class="line">			&#125;			</span><br><span class="line">		&#125;</span><br><span class="line">		&#125;catch (Exception e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	 * 3. 根据不同的事件做处理</span><br><span class="line">	 * @param selector </span><br><span class="line">	 * @param key</span><br><span class="line">	 * @throws IOException </span><br><span class="line">	 */</span><br><span class="line">	private void process(Selector selector, SelectionKey key) throws IOException &#123;</span><br><span class="line">		// 接受请求</span><br><span class="line">		if (key.isAcceptable()) &#123;</span><br><span class="line">			ServerSocketChannel server = (ServerSocketChannel) key.channel();</span><br><span class="line">			SocketChannel channel = server.accept();</span><br><span class="line">			channel.configureBlocking(false);</span><br><span class="line">			channel.register(selector, SelectionKey.OP_READ);</span><br><span class="line">		&#125;</span><br><span class="line">		// 读信息</span><br><span class="line">		else if (key.isReadable()) &#123;</span><br><span class="line">			System.out.println(&quot;读信息&quot;);</span><br><span class="line">			SocketChannel channel = (SocketChannel) key.channel();</span><br><span class="line">			ByteBuffer buffer = ByteBuffer.allocate(1024);</span><br><span class="line">			int count = channel.read(buffer);</span><br><span class="line">			if (count &gt; 0) &#123;</span><br><span class="line">				buffer.flip();</span><br><span class="line">				System.out.println(count);</span><br><span class="line">				byte[] bytes = new byte[1024];</span><br><span class="line">				int i = 0;</span><br><span class="line">				while(buffer.remaining() &gt; 0)&#123;</span><br><span class="line">					byte b = buffer.get();</span><br><span class="line">					bytes[i++] = b;</span><br><span class="line">				&#125;</span><br><span class="line">				System.out.println(new String(bytes,&quot;UTF-8&quot;));</span><br><span class="line">			&#125;else &#123;</span><br><span class="line">				channel.close();</span><br><span class="line">			&#125;</span><br><span class="line">			buffer.flip();</span><br><span class="line">			buffer.clear();</span><br><span class="line">		&#125;</span><br><span class="line">		// 写数据</span><br><span class="line">		else if (key.isWritable()) &#123;</span><br><span class="line">			System.out.println(&quot;写数据&quot;);</span><br><span class="line">			SocketChannel channel = (SocketChannel) key.channel();</span><br><span class="line">//			String name = (String) key.attachment();</span><br><span class="line">			byte[] bytes = &quot;hello&quot;.getBytes(&quot;UTF-8&quot;);</span><br><span class="line">			ByteBuffer buffer = ByteBuffer.allocate(1024);</span><br><span class="line">			System.out.println(bytes.length);</span><br><span class="line">			for(int i = 0;i &lt; bytes.length;i++)&#123;</span><br><span class="line">				buffer.put(bytes[i]);</span><br><span class="line">			&#125;</span><br><span class="line">			buffer.flip();</span><br><span class="line">			channel.write(buffer);</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	public static void main(String[] args) throws IOException &#123;</span><br><span class="line">		NioServer nioServer = new NioServer();</span><br><span class="line">		Selector selector = nioServer.getSelector();</span><br><span class="line">		nioServer.listener(selector);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Client端：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line">public class NioClient &#123;</span><br><span class="line">	</span><br><span class="line">	/**</span><br><span class="line">	 * 连接的端口</span><br><span class="line">	 */</span><br><span class="line">	private static final int PORT = 8001;</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	 * 1. 注册事件 </span><br><span class="line">	 * @throws IOException </span><br><span class="line">	 */</span><br><span class="line">	public void	start() throws IOException &#123;</span><br><span class="line">		// // 创建可选择通道，并配置为非阻塞模式</span><br><span class="line">		SocketChannel socketChannel = SocketChannel.open();				</span><br><span class="line">		socketChannel.configureBlocking(false);</span><br><span class="line">		</span><br><span class="line">		// 连接指定的端口</span><br><span class="line">		InetSocketAddress address = new InetSocketAddress(PORT);</span><br><span class="line">		socketChannel.connect(address);</span><br><span class="line">		</span><br><span class="line">		Selector selector = Selector.open();</span><br><span class="line">		</span><br><span class="line">		// 向Selector中注册感兴趣的事件</span><br><span class="line">		socketChannel.register(selector, SelectionKey.OP_CONNECT);</span><br><span class="line">		</span><br><span class="line">		Scanner scanner = new Scanner(System.in);</span><br><span class="line">		while(true)&#123;</span><br><span class="line">			selector.select();// 连接</span><br><span class="line">			Set&lt;SelectionKey&gt; selectedKeys = selector.selectedKeys();//获取连接</span><br><span class="line">			System.out.println(&quot;selectedKeys.size:&quot;+selectedKeys.size());</span><br><span class="line">			Iterator&lt;SelectionKey&gt; iterator = selectedKeys.iterator();</span><br><span class="line">			while (iterator.hasNext()) &#123;</span><br><span class="line">				SelectionKey key = iterator.next();</span><br><span class="line">				iterator.remove();</span><br><span class="line">				</span><br><span class="line">				if (key.isConnectable()) &#123;</span><br><span class="line">					socketChannel.finishConnect();</span><br><span class="line">					socketChannel.register(selector, SelectionKey.OP_WRITE);</span><br><span class="line">					System.out.println(&quot;server connected...&quot;);</span><br><span class="line">					break;</span><br><span class="line">				&#125;</span><br><span class="line">				else if(key.isWritable())&#123;</span><br><span class="line">					System.out.println(&quot;please input message:&quot;);</span><br><span class="line">					String message = scanner.nextLine();</span><br><span class="line">					ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBytes(&quot;UTF-8&quot;));</span><br><span class="line">					socketChannel.write(byteBuffer);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;			</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	public static void main(String[] args) throws IOException &#123;</span><br><span class="line">		new NioClient().start();</span><br><span class="line">	&#125;	</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>本文示例<a href="http://git.oschina.net/zaitingma/codes/905bwkxai4qjsufy6d7hl97" target="_blank" rel="noopener">代码下载</a><br>更多示例请参考<a href="http://rox-xmlrpc.sourceforge.net/niotut/index.html" target="_blank" rel="noopener">这里</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Java/Java-Mina-2-0-16框架学习使用/" rel="next" title="Java-Mina-2-0-16框架学习使用">
                <i class="fa fa-chevron-left"></i> Java-Mina-2-0-16框架学习使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Java/Java-OkHttp使用/" rel="prev" title="Java-OkHttp使用">
                Java-OkHttp使用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
